<template>
  <div class="user-detail-container">
    <a-page-header
      title="用户详情"
      :sub-title="`用户ID: ${userId}`"
      @back="goBack"
    />
    
    <a-row :gutter="24">
      <a-col :span="8">
        <a-card :bordered="false">
          <template #cover>
            <div class="avatar-wrapper">
              <a-avatar :size="100" :src="userInfo.avatar || 'https://joeschmoe.io/api/v1/random'" />
            </div>
          </template>
          <template #title>{{ userInfo.nickname || '微信用户' }}</template>
          <template #extra>
            <a-tag :color="userInfo.status ? 'green' : 'red'">
              {{ userInfo.status ? '正常' : '禁用' }}
            </a-tag>
          </template>
          <a-descriptions :column="1">
            <a-descriptions-item label="用户名">{{ userInfo.username || '-' }}</a-descriptions-item>
            <a-descriptions-item label="性别">{{ getGenderText(userInfo.gender) }}</a-descriptions-item>
            <a-descriptions-item label="年龄">{{ userInfo.age || '-' }}</a-descriptions-item>
            <a-descriptions-item label="糖尿病类型">{{ getDiabetesTypeText(userInfo.diabetesType) }}</a-descriptions-item>
            <a-descriptions-item label="注册时间">{{ formatDate(userInfo.createTime) }}</a-descriptions-item>
          </a-descriptions>
        </a-card>
      </a-col>
      
      <a-col :span="16">
        <a-card
          title="血糖记录"
          :bordered="false"
          :tabList="[
            { key: 'records', tab: '记录列表' },
            { key: 'statistics', tab: '统计信息' }
          ]"
          :activeTabKey="activeTab"
          @tabChange="handleTabChange"
        >
          <template v-if="activeTab === 'records'">
            <a-table
              :columns="columns"
              :data-source="records"
              :pagination="pagination"
              :loading="loading"
              @change="handleTableChange"
              row-key="id"
              size="middle"
              bordered
            >
              <template #bodyCell="{ column, text, record }">
                <template v-if="column.dataIndex === 'value'">
                  <span :style="{ color: getValueColor(record) }">{{ text }}</span>
                </template>
                
                <template v-if="column.dataIndex === 'measureTypeName'">
                  {{ text }}
                </template>
                
                <template v-if="column.dataIndex === 'status'">
                  <a-tag :color="getStatusTagColor(record.status)">
                    {{ record.statusText }}
                  </a-tag>
                </template>
                
                <template v-if="column.dataIndex === 'measureTime'">
                  {{ formatDateTime(text) }}
                </template>
              </template>
            </a-table>
          </template>
          
          <template v-else-if="activeTab === 'statistics'">
            <a-row :gutter="16" class="stat-cards">
              <a-col :span="8">
                <a-statistic
                  title="总记录数"
                  :value="stats.totalCount || 0"
                  :precision="0"
                />
              </a-col>
              <a-col :span="8">
                <a-statistic
                  title="平均血糖"
                  :value="stats.avgValue || 0"
                  :precision="1"
                  :value-style="{ color: getAvgValueColor() }"
                  suffix="mmol/L"
                />
              </a-col>
              <a-col :span="8">
                <a-statistic
                  title="最近记录"
                  :value="formatDate(stats.latestRecord)"
                />
              </a-col>
            </a-row>
            
            <a-divider />
            
            <div ref="chartRef" style="width: 100%; height: 300px"></div>
          </template>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { message } from 'ant-design-vue';
import axios from 'axios';
import * as echarts from 'echarts/core';
import { GridComponent, TooltipComponent, TitleComponent, LegendComponent } from 'echarts/components';
import { LineChart } from 'echarts/charts';
import { CanvasRenderer } from 'echarts/renderers';

// 注册必须的组件
echarts.use([
  GridComponent,
  TooltipComponent,
  TitleComponent,
  LegendComponent,
  LineChart,
  CanvasRenderer
]);

const route = useRoute();
const router = useRouter();
const userId = ref(route.params.id);
const userInfo = ref({});
const loading = ref(false);
const activeTab = ref('records');
const chartRef = ref(null);
let chart = null;

// 血糖记录列表
const records = ref([]);
const stats = ref({});

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total) => `共 ${total} 条记录`
});

// 表格列定义
const columns = [
  {
    title: '血糖值',
    dataIndex: 'value',
    width: 100
  },
  {
    title: '测量类型',
    dataIndex: 'measureTypeName',
    width: 120
  },
  {
    title: '状态',
    dataIndex: 'status',
    width: 100
  },
  {
    title: '测量时间',
    dataIndex: 'measureTime',
    width: 180
  },
  {
    title: '备注',
    dataIndex: 'remark',
    ellipsis: true
  }
];

// 获取用户详情
const fetchUserDetail = async () => {
  try {
    loading.value = true;
    const response = await axios.get(`/admin/api/users/wx-users/${userId.value}`);
    
    if (response.data.code === 0) {
      userInfo.value = response.data.data;
    } else {
      message.error(response.data.message || '获取用户详情失败');
    }
  } catch (error) {
    console.error('获取用户详情错误', error);
    message.error('获取用户详情失败');
  } finally {
    loading.value = false;
  }
};

// 获取用户血糖记录
const fetchUserRecords = async () => {
  try {
    loading.value = true;
    
    const response = await axios.get('/admin/blood-sugar/list', { 
      params: {
        userId: userId.value,
        page: pagination.current,
        size: pagination.pageSize
      }
    });
    
    if (response.data.code === 0) {
      records.value = response.data.data.records;
      pagination.total = response.data.data.total;
    } else {
      message.error(response.data.message || '获取血糖记录失败');
    }
  } catch (error) {
    console.error('获取血糖记录错误', error);
    message.error('获取血糖记录失败');
  } finally {
    loading.value = false;
  }
};

// 获取用户统计数据
const fetchUserStats = async () => {
  try {
    const response = await axios.get('/admin/blood-sugar/statistics', {
      params: {
        userId: userId.value,
        timeRange: 'month'
      }
    });
    
    if (response.data.code === 0) {
      stats.value = response.data.data;
      
      // 获取趋势数据
      const trendResponse = await axios.get('/admin/blood-sugar/trend', {
        params: {
          userId: userId.value,
          timeRange: 'month'
        }
      });
      
      if (trendResponse.data.code === 0) {
        renderChart(trendResponse.data.data);
      }
    } else {
      message.error(response.data.message || '获取统计数据失败');
    }
  } catch (error) {
    console.error('获取统计数据错误', error);
    message.error('获取统计数据失败');
  }
};

// 渲染图表
const renderChart = (data) => {
  if (!chartRef.value) return;
  
  if (!chart) {
    chart = echarts.init(chartRef.value);
  }
  
  const dates = data.map(item => item.date);
  const values = data.map(item => item.avgValue);
  
  const option = {
    title: {
      text: '近期血糖趋势'
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: dates
    },
    yAxis: {
      type: 'value',
      name: '血糖值 (mmol/L)'
    },
    series: [
      {
        name: '平均血糖',
        type: 'line',
        data: values,
        markLine: {
          data: [
            { 
              name: '正常范围', 
              yAxis: 6.1,
              lineStyle: { color: '#f5222d' } 
            },
            { 
              name: '正常下限', 
              yAxis: 3.9,
              lineStyle: { color: '#faad14' } 
            }
          ]
        },
        smooth: true
      }
    ]
  };
  
  chart.setOption(option);
};

// 处理标签页切换
const handleTabChange = (key) => {
  activeTab.value = key;
  
  if (key === 'records') {
    fetchUserRecords();
  } else if (key === 'statistics') {
    fetchUserStats();
  }
};

// 表格变化处理
const handleTableChange = (pag) => {
  pagination.current = pag.current;
  pagination.pageSize = pag.pageSize;
  fetchUserRecords();
};

// 性别文本映射
const getGenderText = (gender) => {
  const genderMap = {
    1: '男',
    2: '女',
    0: '未知'
  };
  return genderMap[gender] || '未知';
};

// 糖尿病类型文本映射
const getDiabetesTypeText = (type) => {
  const typeMap = {
    1: '1型糖尿病',
    2: '2型糖尿病',
    3: '妊娠糖尿病',
    4: '其他类型'
  };
  return typeMap[type] || '未知';
};

// 获取血糖值状态颜色
const getValueColor = (record) => {
  if (!record.status) return '';
  
  switch (record.status) {
    case 1: return '#52c41a'; // 正常
    case 2: return '#faad14'; // 偏低
    case 3: return '#f5222d'; // 偏高
    default: return '';
  }
};

// 获取状态标签颜色
const getStatusTagColor = (status) => {
  if (!status) return '';
  
  switch (status) {
    case 1: return 'green'; // 正常
    case 2: return 'orange'; // 偏低
    case 3: return 'red'; // 偏高
    default: return '';
  }
};

// 获取平均血糖颜色
const getAvgValueColor = () => {
  const avgValue = stats.value.avgValue;
  if (!avgValue) return '';
  
  if (avgValue < 3.9) {
    return '#faad14'; // 偏低
  } else if (avgValue > 6.1) {
    return '#f5222d'; // 偏高
  } else {
    return '#52c41a'; // 正常
  }
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '-';
  const date = new Date(dateString);
  return date.toLocaleDateString('zh-CN');
};

// 格式化日期和时间
const formatDateTime = (dateString) => {
  if (!dateString) return '-';
  const date = new Date(dateString);
  return date.toLocaleString('zh-CN');
};

// 返回上一页
const goBack = () => {
  router.go(-1);
};

// 窗口大小调整时重新渲染图表
const handleResize = () => {
  chart?.resize();
};

onMounted(() => {
  fetchUserDetail();
  fetchUserRecords();
  window.addEventListener('resize', handleResize);
});

onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  chart?.dispose();
});
</script>

<style scoped>
.user-detail-container {
  padding: 24px;
}

.avatar-wrapper {
  display: flex;
  justify-content: center;
  padding: 24px 0;
  background-color: #f5f5f5;
}

.stat-cards {
  margin-bottom: 24px;
}
</style> 